﻿package ygg.encoding.amf.type.v3
{
	import ygg.encoding.amf.type.*;
	import ygg.encoding.amf.*;
	import j.sus2maj7.encoding.*;
	
	public class ComplexCodec extends Amf3Codec
	{
		public function ComplexCodec()
		{
			
		}
		
		override public function decode(binary:IBinary, context:IContext=null):*
		{
			var u:uint = AmfBinary(binary).decodeU29();
			
			if ( u & 1 ) //U29x-value
			{
				var o:* = decodeComplex(u >>> 1, binary, context);
				AmfContext(context).addComplex(o);
				return o;
			}
			else //u29x-ref
			{
				return AmfContext(context).getComplex( u >>> 1 );
			}
			
		}
		
		override public function encode(o:*, context:IContext=null):IBinary
		{
			trace('complex encode');
			//check if already in reference table
			var i:int = AmfContext(context).indexOfComplex(o);
			
			trace('indexOfComplex', i);
			
			var b:AmfBinary = new AmfBinary();
			b.writeByte( getMarker() );
			
			if ( i > -1 ) //u29x-ref x0
			{
				trace('u29x-ref');
				i <<= 1;
				//i |= 0;
				
				b.encodeU29(i);
			}
			else //U29x-value
			{
				trace('U29x-value');
				
				AmfContext(context).addComplex(o);
				encodeComplex(o, b, context);
			}
			
			return b;
		}
		
		
		protected function decodeComplex(u:uint, binary:IBinary, context:IContext=null):*
		{
			//override in derived
			return null;
		}
		protected function encodeComplex(o:Object, binary:IBinary, context:IContext=null):void
		{
			
		}
		protected function getMarker():uint
		{
			return 0;
		}
	}
	
}